package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.common.exception.YYGHException;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.acl.User;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.PatientMapper;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-03-11
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private PatientMapper patientMapper;

    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        String openid = loginVo.getOpenid();
        //1.获取用户的手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //2.对用户的手机号和验证码进行非空校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            throw new YYGHException(20001,"用户信息有误");
        }
        //TODO: 将用户输入的验证码和redis中的验证码做一个比对
        String redisCode = redisTemplate.opsForValue().get(phone);

        if(StringUtils.isEmpty(redisCode) || !redisCode.equals(code)){
            throw new YYGHException(20001,"验证码有误");
        }
        UserInfo userInfo=null;
        //openid为空:单纯的手机号登录
        if(StringUtils.isEmpty(openid)){
           //3.确定用户是否是首次登录，
            QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<UserInfo>();
            queryWrapper.eq("phone",phone);

            userInfo = baseMapper.selectOne(queryWrapper);
            if(userInfo == null){//是首次登录，则需要注册一份
                userInfo=new UserInfo();
                userInfo.setStatus(1);
                userInfo.setPhone(phone);
                baseMapper.insert(userInfo);
            }


        }else{

            UserInfo userInfoFinal=new UserInfo();


            QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<UserInfo>();
            queryWrapper.eq("phone",phone);

            userInfo = baseMapper.selectOne(queryWrapper);
            if(userInfo != null){
                BeanUtils.copyProperties(userInfo,userInfoFinal);
                baseMapper.deleteById(userInfo.getId());
            }else{
                userInfoFinal.setPhone(phone);
            }

            //openid不为空:微信绑定手机号登录
            QueryWrapper<UserInfo> queryWrapper1=new QueryWrapper<UserInfo>();
            queryWrapper1.eq("openid",openid);
            userInfo = baseMapper.selectOne(queryWrapper1);
            //userInfo.setPhone(phone);
            userInfoFinal.setOpenid(openid);
            userInfoFinal.setNickName(userInfo.getNickName());
            userInfoFinal.setId(userInfo.getId());
            baseMapper.updateById(userInfoFinal);

        }

       //4.验证用户的状态是否被锁定：被锁定，抛出异常
        if(userInfo.getStatus()==0){
            throw new YYGHException(20001,"用户被锁定");
        }

        //5.返回页面用户信息
        Map<String, Object> map = new HashMap<>();

        String name = userInfo.getName();

        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token",token);
        return map;
    }

    @Override
    public UserInfo selectById(Long userId) {
        UserInfo userInfo1 = baseMapper.selectById(userId);
        userInfo1.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo1.getAuthStatus()));
        return userInfo1;
    }

    @Override
    public void saveUserAuthInfo(Long userId, UserAuthVo userAuthVo) {

        UserInfo userInfo1 = new UserInfo();
        userInfo1.setId(userId);


        userInfo1.setName(userAuthVo.getName());
        userInfo1.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo1.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo1.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo1.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());

        baseMapper.updateById(userInfo1);
    }

    @Override
    public Page<UserInfo> getUserInfoPageByQueryCondition(Integer pageNum, Integer limit, UserInfoQueryVo userInfoQueryVo) {
        Page<UserInfo> page=new Page<UserInfo>(pageNum,limit);
        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<UserInfo>();
        String keyword = userInfoQueryVo.getKeyword();//用户名称或者手机号
        Integer status = userInfoQueryVo.getStatus();
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();

        if(!StringUtils.isEmpty(keyword)){
            queryWrapper.like("name",keyword).or().eq("phone",keyword);
        }
        if(!StringUtils.isEmpty(status)) {
            queryWrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            queryWrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            queryWrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            queryWrapper.le("create_time",createTimeEnd);
        }

        baseMapper.selectPage(page,queryWrapper);

        page.getRecords().parallelStream().forEach(item->{
            this.packageUserInfo(item);
        });
        return page;
    }

    private void packageUserInfo(UserInfo item) {
        item.getParam().put("statusString",item.getStatus()==0?"锁定":"正常");
        item.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(item.getAuthStatus()));
    }


    @Override
    public void lock(Integer id, Integer status) {
        if(status == 0 || status == 1){
            UserInfo userInfo1 =baseMapper.selectById(id);
            userInfo1.setStatus(status);
            baseMapper.updateById(userInfo1);
        }

    }

    @Override
    public Map<String, Object> show(Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();

        UserInfo userInfo1 = baseMapper.selectById(id);
        map.put("userInfo",userInfo1);
        QueryWrapper<Patient> queryWrapper=new QueryWrapper<Patient>();
        queryWrapper.eq("user_id",id);
        List<Patient> patientList = patientMapper.selectList(queryWrapper);
        map.put("patientList",patientList);
        return map;
    }

    @Override
    public void approval(Long userId, Integer authStatus) {
        if(authStatus.intValue()==2 || authStatus.intValue()==-1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }
}
